<?php

namespace App\Http\Controllers\Api;

use App\Models\DiscountGoods;
use Carbon\Carbon;
use App\Models\{CarFavourite,
    FrontForum,
    GoodsCommon,
    GroupbuyBase,
    MbPageSett,
    MbTplLayout,
    Pintuan,
    RedpacketBase,
    RedpacketTemplate,
    RedRain,
    RedRainList,
    RedRainUse,
    UserFootprint,
    VoucherBase,
    VoucherTemp,
    WebConfig};

class IndexController extends Controller
{
    public function index()
    {
        $result_data = \Cache::remember(config('app.home_page_cache_key'), config('app.home_page_cache_ttl'), function () {
            $data = [];
            $layouts = MbTplLayout::getEnableLayouts();
            $layouts->each(function ($layout, $index) use (&$data) {
                switch ($layout->mb_tpl_layout_type) {
                    case 'adv_list': // 头部滚动条
                        $slide_items = [];
                        foreach ($layout->mb_tpl_layout_data as $v) {
                            $item = [];
                            $item['image'] = $v['image'];
                            $item['type'] = $v['image_type'];
                            $item['data'] = $v['image_data'];
                            $slide_items[] = $item;
                        }
                        if (!empty($slide_items)) {
                            $data[$index + 1]['slider_list']['item'] = $slide_items;
                        }
                        break;
                    case 'home1':
                        $hom1 = [];
                        $mb_tpl_layout_data = $layout->mb_tpl_layout_data;
                        $hom1['title'] = $layout->mb_tpl_layout_title;
                        $hom1['image'] = $mb_tpl_layout_data['image'];
                        $hom1['type'] = $mb_tpl_layout_data['image_type'];
                        $hom1['data'] = $mb_tpl_layout_data['image_data'];
                        $data[$index + 1]['home1'] = $hom1;
                        break;
                    case 'home3':
                        $home3 = [];
                        $item = [];
                        foreach ($layout->mb_tpl_layout_data as $key => $layout_data) {
                            $item[$key]['image'] = $layout_data['image'];
                            $item[$key]['type'] = $layout_data['image_type'];
                            $item[$key]['data'] = $layout_data['image_data'];
                        }
                        $home3['item'] = $item;
                        $home3['title'] = $layout->mb_tpl_layout_title;
                        $data[$index + 1]['home3'] = $home3;
                        break;
                    case 'goods':
                    case 'goodsB':
                        $goods = [];
                        $item = [];
                        GoodsCommon::findByIds($layout->mb_tpl_layout_data)->each(function ($goodCommon, $i) use (&$data, $layout, $index, &$item) {
                            $item[$i]['goods_id'] = $goodCommon->getGoodsId();
                            $item[$i]['goods_name'] = $goodCommon->common_name;
                            $item[$i]['goods_promotion_price'] = $goodCommon->common_price;
                            $item[$i]['goods_image'] = image_thumb($goodCommon->common_image, 360);
                            $item[$i]['goods_salenum'] = $goodCommon->common_salenum;
                            $item[$i]['goods_evaluation_count'] = $goodCommon->common_evaluate;
                        });
                        $goods['item'] = array_values($item);
                        $goods['title'] = $layout->mb_tpl_layout_title;
                        $data[$index + 1][$layout->mb_tpl_layout_type] = $goods;
                        break;
                    case 'enterance':
                        $enterance = [];
                        $item = [];
                        foreach ($layout->mb_tpl_layout_data as $key => $layout_data) {
                            $item[$key]['icons'] = $layout_data['icons'];
                            $item[$key]['navName'] = $layout_data['navName'];
                            $item[$key]['url'] = $layout_data['url'];
                            $item[$key]['types'] = $layout_data['types'];
                        }
                        $enterance['item'] = $item;
                        $enterance['title'] = $layout->mb_tpl_layout_title;
                        $data[$index + 1]['enterance'] = $enterance;
                        break;
                    case 'home2':
                    case 'home4':
                    case 'advA':
                    case 'advB':
                    case 'goodsC':
                    case 'goodsD':
                    case 'goodsE':
                        $adv = [];
                        $start = in_array($layout->mb_tpl_layout_type, ['goodsC', 'goodsD', 'goodsE']) ? 3 : 1;
                        $end = in_array($layout->mb_tpl_layout_type, ['home2', 'home4']) ? 2 : ($layout->mb_tpl_layout_type == 'advB' ? 5 : 6);
                        $mb_tpl_layout_data = $layout->mb_tpl_layout_data;
                        $adv['title'] = $layout->mb_tpl_layout_title;
                        for ($i = $start; $i <= $end; $i++) {
                            $adv["rectangle{$i}_image"] = array_get(array_get($mb_tpl_layout_data, "rectangle{$i}"), 'image');
                            $adv["rectangle{$i}_type"] = array_get(array_get($mb_tpl_layout_data, "rectangle{$i}"), 'image_type');
                            $adv["rectangle{$i}_data"] = array_get(array_get($mb_tpl_layout_data, "rectangle{$i}"), 'image_data');
                        }
                        if (!in_array($layout->mb_tpl_layout_type, ['advB'])) {
                            $adv['square_image'] = array_get(array_get($mb_tpl_layout_data, 'square'), 'image');
                            $adv['square_type'] = array_get(array_get($mb_tpl_layout_data, 'square'), 'image_data');
                            $adv['square_data'] = array_get(array_get($mb_tpl_layout_data, 'square'), 'image_data');
                        }
                        $data[$index + 1][$layout->mb_tpl_layout_type] = $adv;
                        break;
                    case 'activityA':
                    case 'activityB':
                    case 'activityC':
                        $activity = [];
                        $item = [];
                        foreach ($layout->mb_tpl_layout_data as $key => $layout_data) {
                            switch ($layout_data['type']) {
                                case 'groupbuy': // 团购
                                    $content_info = GroupbuyBase::getForumGroupbuy(explode(',', $layout_data['content']));
                                    if ($layout->mb_tpl_layout_type == 'activityA') {
                                        $num = 12 - count($content_info);
                                    } else {
                                        $num = 2 - count($content_info);
                                    }
                                    if ($num > 0) {
                                        $content = FrontForum::addOpenForumContent($layout_data['type'], explode(',', $layout_data['content']), $num);
                                        if ($content) {
                                            $content_info = array_merge($content_info, $content);
                                        }
                                    }
                                    $layout_data['content_info'] = array_values($content_info);
                                    break;
                                case 'discount': // 限时折扣
                                    $discountGoods = DiscountGoods::getDiscountGoodsByIds(explode(',', $layout_data['content']));
                                    if ($layout->mb_tpl_layout_type == 'activityA') {
                                        $num = 12 - $discountGoods->count();
                                    } else {
                                        $num = 3 - $discountGoods->count();
                                    }

                                    if ($num > 0) {
                                        $content = FrontForum::addOpenForumContent($layout_data['type'], explode(',', $layout_data['content']), $num);
                                        $discountGoods = $discountGoods->merge($content);
                                    }

                                    $layout_data['content_info'] = $discountGoods->toArray();
                                    break;
                                case 'pintuan': // 拼团
                                    $pintuanGoods = Pintuan::getPintuanGoodsByIds();
                                    if ($layout->mb_tpl_layout_type == 'activityA') {
                                        $num = 12 - $pintuanGoods->count();
                                    } else {
                                        $num = 2 - $pintuanGoods->count();
                                    }

                                    if ($num > 0) {
                                        $content = FrontForum::addOpenForumContent($layout_data['type'], explode(',', $layout_data['content']), $num);
                                        $pintuanGoods = $pintuanGoods->merge($content);
                                    }
                                    $layout_data['content_info'] = $pintuanGoods->toArray();
                                    break;
                                case 'redpacket': // 红包
                                case 'voucher': // 代金券
                                    $layout_data['content_info'] = $layout_data['content'];
                                    break;
                            }
                            $item[$key]['title'] = $layout_data['title'];
                            $item[$key]['content_info'] = $layout_data['content_info'];
                            $item[$key]['content'] = $layout_data['content'];
                            $item[$key]['type'] = $layout_data['type'];
                        }

                        $activity['item'] = current($item);
                        if ($layout->mb_tpl_layout_type == 'activityB') {
                            $activity['item'] = $item;
                        }
                        $activity['title'] = $layout->mb_tpl_layout_title;
                        $data[$index + 1][$layout->mb_tpl_layout_type] = $activity;
                }
            });

            $result_data = [];
            $mbPageSetts = MbPageSett::getByCats([1, 2, 3]);
            // 猜你喜欢
            $result_data['favourite_goods'] = UserFootprint::userFavorite();
            // 红包雨
            $result_data['itemns']['rain_red'] = RedRain::getOneAsArray();
            $result_data['itemns']['bg_img'] = array_values($mbPageSetts->where('cat', 1)->toArray());
            $result_data['itemns']['redp_img'] = array_values($mbPageSetts->where('cat', 2)->toArray());
            $result_data['itemns']['lunbo_img'] = array_values($mbPageSetts->where('cat', 3)->toArray());
            $result_data['module_data'] = array_values($data);
            $result_data['site_logo'] = WebConfig::value("setting_logo");
            // 是否显示红包弹框
            $result_data['red_status'] = 1;
            // 我的爱车
            $result_data['favourite_car'] = [];

            return $result_data;
        });

        $voucher_t_ids = [];
        $redpacket_t_ids = [];
        // 尝试获取已绑定手机的登录用户信息
        $user = auth('api')->user();

//        var_dump($user);exit;
        if ($user && $user->user_id) {
            // 猜你喜欢
            $result_data['favourite_goods'] = UserFootprint::userFavorite($user->user_id);

            if ($result_data['itemns']['rain_red']) {
                $result_data['itemns']['rain_red']['stat'] = 0;
                if ($redRainUse = RedRainUse::whereUserId($user->user_id)->whereDate('dattime', now()->toDateString())->latest('id')->first()) {
                    $result_data['itemns']['rain_red']['stat'] = 1;
                }
                if ($result_data['itemns']['rain_red']['templs'] == 2) {
                    $result_data['itemns']['rain_red']['list1'] = RedRainList::getByRainId($result_data['itemns']['rain_red']['rain_id'])->toArray();
                }
            }

            // 我的爱车
            $result_data['favourite_car'] = CarFavourite::getFavouriteCars($user->user_id)->first()->toArray();

            // 用户拥有的优惠券
            $voucher_t_ids = VoucherBase::getVoucherTIdsByUserIdAsArray($user->user_id);
            // 用户拥有的红包
            $redpacket_t_ids = RedpacketBase::getRedpacketTIdsByUserIdAsArray($user->user_id);
        }

        $enableVouchers = VoucherTemp::getEnableVouchers();
        $canShowVouchers = $enableVouchers->when(!empty($voucher_t_ids), function ($canShowVouchers) use ($voucher_t_ids) {
            return $canShowVouchers->whereNotIn('voucher_t_id', $voucher_t_ids);
        })
            ->filter(function ($voucher) {
                return $voucher->voucher_t_total > $voucher->voucher_t_giveout;
            })
            ->each(function ($voucher) {
                $voucher->stats = 1;
                $voucher->voucher_t_start_date1 = Carbon::parse($voucher->voucher_t_start_date)->format('Y/m/d');
                $voucher->voucher_t_end_date1 = Carbon::parse($voucher->voucher_t_end_date)->format('Y/m/d');
            })
            ->toArray();

        $enableRedpackets = RedpacketTemplate::getEnableRedpackets();
        $canShowRedpackets = $enableRedpackets->when(!empty($redpacket_t_ids), function ($enableRedpackets) use ($redpacket_t_ids) {
            return $enableRedpackets->whereNotIn('redpacket_t_id', $redpacket_t_ids);
        })
            ->filter(function ($redpacket) {
                return $redpacket->redpacket_t_total > $redpacket->redpacket_t_giveout;
            })
            ->each(function ($redpacket) {
                $redpacket->stats = 2;
                $redpacket->redpacket_t_start_date1 = Carbon::parse($redpacket->redpacket_t_start_date)->format('Y/m/d');
                $redpacket->redpacket_t_end_date1 = Carbon::parse($redpacket->redpacket_t_end_date)->format('Y/m/d');
            })
            ->toArray();

        $result_data['v'] = array_merge($canShowVouchers, $canShowRedpackets);

        return $this->success($result_data);
    }
}
